import './style.css'
import { 
  Button, 
  Input, 
  DatePicker, 
  Table, 
  Switch, 
  message, 
  Popconfirm,
  Space
} from 'antd'
import { EditOutlined, DeleteFilled } from '@ant-design/icons'
import { useState, useEffect} from 'react'
import CustomModal from 'components/Modal'
import { withRouter } from 'react-router-dom'
import { delData } from 'utils/local'
import { getProducts, addProduct, updateProduct, deleProduct } from 'api'
function List(props) {

  /* 选中时间控件改变 */
  const dateChange = (date, local) => {}

  /* 添加商品对话框显示 */
  const [visible, setVisible] = useState(false)
  const showModal = () => {
    setVisible(true)
  }
  const hideModal = () => {
    setVisible(false)
  }



   /* 在此发送添加商品请求 */
   const ok = (fields, close) => {
    addProduct(fields)
    .then( ({ data }) => {
      if (data.state) {
        close()
      }
      message[data.state ? "success" : 'error'](data.msg, .8)
      /* 添加成功后重新获取商品列表 */
      getList()
    })
    .catch(() => close())
  }




  /* 修改商品对话框显示 */
  const [editVisible, toggleEdit] = useState(false)
  /* 修改时存储的商品信息 */
  const [initValue, setInitValue] = useState(null)
  /* 保存需要修改的数据 */
  const showEdit = (row) => {
    setInitValue(row)
    toggleEdit(true)
  }
  const hideEdit = () => {
    toggleEdit(false)
  }
  /* 修改后的数据进行传输 */
  const editOk = (fields) => {
    updateProduct(
      Object.assign(
          fields, 
          { 
            product_id: initValue.product_id 
          }
        )
      )
    .then( ({ data }) => {
      if (data.status !== 1004 
        && data.status !== 1005 
        && data.status !== 200) {
        message.warn('登录过期,请重新登录!')

        delData('token')
        setTimeout(()=>  props.history.push('/login'), 888)

      } else if (data.state) {
        message.success('修改成功')
        /* 修改成功后才能重新获取数据并关闭modal */
        getList()
        toggleEdit(false)
      }
      
    })
  }




  /*获取商品 */
  const [list, setList] = useState([])
  const getList = () => {
    getProducts()
    .then( value => {
      if (value.data.state) {
        setList(value.data.data)
      }
    })
  }




  // 删除数据的函数
  const deleteProduct = id =>  deleProduct(id).then(({ data })=>{
    if (data.state) {
      return  data
    }
  })




   /* 存放表格选中状态 */
   const [decide, setDecide] = useState([])
   /* 删除多头数据使用递归 */
   const deleteRow = () => {
     let index = 0
     const again = () => {
       console.log(decide[index])
       if (decide[index]) {
        deleteProduct(decide[index++])
        .then( value => {
          if (value?.state) {
            again()
          }
        } )
         
       } else {
         /* 数组中的数据获取不到时就是全部删除完成后，提示删除的信息 */
        message.success('成功删除'+ index +'个商品', .8)
        /* 删除完成后清除选中的商品数组 */
        setDecide([])
        getList()
       }
     }
     again()
     
   }
  /* 删除一条数据 */
  const deleRow = row => {
    deleteProduct(row.product_id)
    .then( data => {
      if (data.state) {
        message.success(data.msg, .8)
        getList()
      }
    } )
  }





  /* 保证只在初次渲染时调用，获取商品的数据展示 */
  useEffect(()=>{
    getList()
  },[])

   /* 表格头 */
 const columns = [ 
    {
      title: '商品名称',
      dataIndex: 'productName',
      key: ''
    },
    {
      title: '商品库存' ,
      dataIndex: 'inventory',
    },
    {
      title: '商品价格',
      dataIndex: 'price',
      key: ''
    },
    {
      title: '是否上架',
      dataIndex: 'inventory',
      render(show) {
        return (
          <Switch checked={show > 0} />
        )
      }

    },
    {
      title: '操作',
      render(row) {
        return (
            <Space>
              <Button 
                type="primary" 
                onClick={()=> showEdit(row)} 
                icon={<EditOutlined />}
              ></Button>
              <Popconfirm
                onConfirm={()=>deleRow(row)}
              >
                <Button 
                  type="danger" 
                  icon={<DeleteFilled />}
                ></Button>
              </Popconfirm>
            </Space>
        )
      }
    }
  ]

  return (
    <div className="productList">
      {/* 操作按钮 */}
        <div className="list-header">

          <Space>
            <Button 
              type="primary" 
              onClick={showModal}
            >添加商品</Button>
            <Popconfirm
              onConfirm={deleteRow}
            > 
              <Button 
                type="danger" 
              >批量删除</Button>
            </Popconfirm>
            
          </Space>

          <div>
            <span>商品内容: </span>
            <Input 
              className="header-input" 
              placeholder="商品名称" 
            /> 
            &nbsp;
            <span>添加时间: </span>
            <DatePicker 
              onChange={dateChange} 
            />
          </div>

        </div>
        {/* 数据的主体内容 */}
        <div className='list-table'>

          <Table 
            rowSelection={{
              onChange(ids) {
                setDecide(ids)
              }
            }} 
            columns={columns} 
            dataSource={list} rowKey="product_id"
            scroll={{ y: 420 }}
          />

        </div>

        {/* 添加对话框 */}
        <CustomModal 
          title='添加商品' 
          visible={visible} 
          cancel={hideModal} 
          ok={ok}
        /> 
        {/* 修改对话框 */}
        {editVisible && <CustomModal 
          title='修改商品' 
          visible={editVisible}
          initValue={initValue}
          cancel={hideEdit}
          ok={editOk}
        /> }
    </div>
  )
}

List.auth = true
List.exact = false
List.meta = {
  name: '商品列表',
  icon: 'icon-liebiao'
}

export default withRouter(List)